package me.firstapp.service.weixin.account.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import me.firstapp.common.utils.DateUtils;
import me.firstapp.common.utils.MD5Utils;
import me.firstapp.module.weixin.jinbi.JinBiAccount;
import me.firstapp.module.weixin.jinbi.JinBiAccountTrace;
import me.firstapp.module.weixin.member.Member;
import me.firstapp.module.weixin.system.AccountRecordType;
import me.firstapp.module.weixin.system.ThisSystem;
import me.firstapp.module.weixin.weibi.WeiBiAccount;
import me.firstapp.module.weixin.weibi.WeiBiAccountTrace;
import me.firstapp.module.weixin.weibi.WeiBiAccountTrace.ChangeType;
import me.firstapp.repository.weixin.jinbi.JinBiAccountRepository;
import me.firstapp.repository.weixin.jinbi.JinBiAccountTraceRepository;
import me.firstapp.repository.weixin.member.MemberRepository;
import me.firstapp.repository.weixin.system.ThisSystemRepository;
import me.firstapp.repository.weixin.weibi.WeiBiAccountRepository;
import me.firstapp.repository.weixin.weibi.WeiBiAccountTraceRepository;
import me.firstapp.service.weixin.account.WeiBiAccountService;

@Service
public class WeiBiAccountServiceImpl implements WeiBiAccountService {

	private static Logger logger = LoggerFactory.getLogger(WeiBiAccountServiceImpl.class);

	@Autowired
	private WeiBiAccountRepository weiBiAccountRepository;

	@Autowired
	private WeiBiAccountTraceRepository weiBiAccountTraceRepository;

	@Autowired
	private JinBiAccountRepository jinBiAccountRepository;

	@Autowired
	private JinBiAccountTraceRepository jinBiAccountTraceRepository;

	@Autowired
	private MemberRepository memberRepository;

	@Autowired
	private ThisSystemRepository thisSystemRepository;

	@Override
	public WeiBiAccount findWeiBiAccountByCardNoAndOpenId(String cardNo, String openId) {
		return weiBiAccountRepository.findWeiBiAccountByCardNoAndOpenId(cardNo, openId);
	}

	@Override
	public List<WeiBiAccount> findWeiBiAccounts(int pageNo, int pageSize) {
		return weiBiAccountRepository.findWeiBiAccounts(pageNo, pageSize);
	}

	@Override
	public JinBiAccountTrace executeExchangeJinBi(WeiBiAccount weiBiAccount) {
		Member member = memberRepository.findMemberByOpenId(weiBiAccount.getOpenId());
		if (Member.STATUS_NO_USE == member.getStatus() || Member.FOLLOW_STATUS_NO == member.getFollowStatus()) {
			logger.info("用户【" + weiBiAccount.getCardNo() + "】被禁用或取消关注，不进行积分结算贝币");
			return null;
		}
		if (!MD5Utils.verify(weiBiAccount.getBalance().doubleValue() * 10000 + "", weiBiAccount.getEncryption())) {
			logger.info("用户【" + weiBiAccount.getCardNo() + "】的积分账户金额异常!");
			return null;
		}
		if (weiBiAccount.getBalance().doubleValue() <= 0.000099) {
			return null;
		}
		JinBiAccount jinBiAccount = jinBiAccountRepository.findJinBiAccountByCardNoAndOpenId(weiBiAccount.getCardNo(),
				weiBiAccount.getOpenId());
		if (!MD5Utils.verify(jinBiAccount.getBalance().doubleValue() * 10000 + "", jinBiAccount.getEncryption())) {
			logger.info("用户【" + jinBiAccount.getCardNo() + "】的贝币账户金额异常!");
			return null;
		}
		ThisSystem thisSystem = thisSystemRepository.findThisSystem();
		BigDecimal rate = BigDecimal.ZERO;
		if (Member.VIP_LEVEL_FANS == member.getVipLevel()) {
			rate = thisSystem.getFansWeibiToJinbiRate();
		} else if (Member.VIP_LEVEL_BASE == member.getVipLevel()) {
			rate = thisSystem.getVipWeibiToJinbiRate();
		} else if (Member.VIP_LEVEL_HIGHT == member.getVipLevel()) {
			rate = thisSystem.getAgenterWeibiToJinbiRate();
		} 
//		else if (Member.VIP_LEVEL_PARTNER == member.getVipLevel()) {
//			rate = thisSystem.getPartnerWeibiToJinbiRate();
//		}
		BigDecimal changeValue = weiBiAccount.getBalance().multiply(rate).multiply(new BigDecimal(0.1)).setScale(4, RoundingMode.HALF_UP);
		if (changeValue.doubleValue() <= 0.00009999) {
			return null;
		}
		WeiBiAccountTrace weiBiAccountTrace = new WeiBiAccountTrace();
		weiBiAccountTrace.setWeiBiAccountId(weiBiAccount.getId());
		weiBiAccountTrace.setChangeType(ChangeType.JINBI_SUB_WEIBI);
		weiBiAccountTrace.setBeforeValue(weiBiAccount.getBalance());
		weiBiAccountTrace.setChangeValue(changeValue);
		BigDecimal afterValue = weiBiAccount.getBalance().subtract(changeValue).setScale(4, RoundingMode.HALF_UP);
		weiBiAccountTrace.setAfterValue(afterValue);
		weiBiAccountTrace.setChangeDate(
				Integer.valueOf(DateUtils.getDateStr(DateUtils.getBeforeOrNextDay(new Date(), -1), "yyyyMMdd")));
		weiBiAccountTrace.setChangeTime(new Date());
		weiBiAccountTraceRepository.save(weiBiAccountTrace);

		weiBiAccount.setBalance(afterValue);
		weiBiAccount.setEncryption(MD5Utils.generate(afterValue.doubleValue() * 10000 + ""));
		weiBiAccount.setUpdateTime(new Date());
		weiBiAccountRepository.update(weiBiAccount);

		JinBiAccountTrace jinBiAccountTrace = new JinBiAccountTrace();
		jinBiAccountTrace.setJinBiAccountId(jinBiAccount.getId());
		jinBiAccountTrace.setChangeType(me.firstapp.module.weixin.jinbi.JinBiAccountTrace.ChangeType.WEIBI_ADD_JINBI);
		jinBiAccountTrace.setBeforeValue(jinBiAccount.getBalance());
		jinBiAccountTrace.setChangeValue(changeValue);
		BigDecimal jinbiAfterValue = jinBiAccount.getBalance().add(changeValue).setScale(4, RoundingMode.HALF_UP);
		jinBiAccountTrace.setAfterValue(jinbiAfterValue);
		jinBiAccountTrace.setChangeDate(
				Integer.valueOf(DateUtils.getDateStr(DateUtils.getBeforeOrNextDay(new Date(), -1), "yyyyMMdd")));
		jinBiAccountTrace.setChangeTime(new Date());
		jinBiAccountTraceRepository.save(jinBiAccountTrace);

		jinBiAccount.setBalance(jinbiAfterValue);
		jinBiAccount.setEncryption(MD5Utils.generate(jinbiAfterValue.doubleValue() * 10000 + ""));
		jinBiAccount.setUpdateTime(new Date());
		jinBiAccountRepository.update(jinBiAccount);

		logger.info(
				"卡号" + weiBiAccount.getCardNo() + "的积分在日期" + DateUtils.getDateStr(new Date(), "yyyyMMdd") + "兑换"+changeValue+"贝币成功");
		return jinBiAccountTrace;
	}

	@Override
	public WeiBiAccountTrace executeTzWeiBiAccount(Long id, ChangeType changeType, BigDecimal tzValue) {
		WeiBiAccount weiBiAccount = (WeiBiAccount) weiBiAccountRepository.getById(id);
		WeiBiAccountTrace weiBiAccountTrace = new WeiBiAccountTrace();
		weiBiAccountTrace.setWeiBiAccountId(weiBiAccount.getId());
		weiBiAccountTrace.setChangeType(changeType);
		weiBiAccountTrace.setBeforeValue(weiBiAccount.getBalance());
		weiBiAccountTrace.setChangeValue(tzValue);
		BigDecimal afterValue = BigDecimal.ZERO;
		if (changeType.getAccountRecordType() == AccountRecordType.ADD) {
			afterValue = weiBiAccount.getBalance().add(tzValue).setScale(4, RoundingMode.HALF_UP);
		} else if (changeType.getAccountRecordType() == AccountRecordType.SUB) {
			afterValue = weiBiAccount.getBalance().subtract(tzValue).setScale(4, RoundingMode.HALF_UP);
		}
		weiBiAccountTrace.setAfterValue(afterValue);
		weiBiAccountTrace.setChangeDate(Integer.valueOf(DateUtils.getDateStr(new Date(), "yyyyMMdd")));
		weiBiAccountTrace.setChangeTime(new Date());
		weiBiAccountTraceRepository.save(weiBiAccountTrace);

		weiBiAccount.setBalance(afterValue);
		weiBiAccount.setEncryption(MD5Utils.generate(afterValue.doubleValue() * 10000 + ""));
		weiBiAccount.setUpdateTime(new Date());
		weiBiAccountRepository.update(weiBiAccount);

		return weiBiAccountTrace;
	}

	@Override
	public List<WeiBiAccount> findWeiBiAccountsForRank(int limitCount) {
		return weiBiAccountRepository.findWeiBiAccountsForRank(limitCount);
	}

	@Override
	public Integer findWeiBiAccountsCounts() {
		return weiBiAccountRepository.findWeiBiAccountsCounts();
	}

	@Override
	public WeiBiAccount findById(Long id) {
		return (WeiBiAccount) weiBiAccountRepository.getById(id);
	}

}
